#include "include/RichText.h"

#include <QTextBlock>
#include <QTextCursor>

#include <fstream>
#include <QSettings>
#include <QFileInfo>
#include <QDir>


QList<QString> RichText::getImageResourceNames(QTextDocument* pDoc)
{
	Q_UNUSED(pDoc);
	return QList<QString>();
}

bool RichText::containsImages(QTextDocument* pDoc)
{
	Q_UNUSED(pDoc);
	return false;
}

QImage RichText::getLastImage(QTextDocument* pDoc)
{
	Q_UNUSED(pDoc);
	return QImage();
}

void RichText::alignAllText(QTextDocument* pDoc, Qt::AlignmentFlag alignment)
{
	if (pDoc == 0)
		return;

	for (QTextBlock block = pDoc->begin(); block != pDoc->end(); block = block.next())
	{
		QTextBlockFormat fmt = block.blockFormat();
		fmt.setAlignment(alignment);

		QTextCursor c(block);
		c.setBlockFormat(fmt);
	}
}


QString RichText::appendImage(QString html, QString imageResourceName)
{
	QString imageElement = buildImageTag(imageResourceName);
	return !html.isEmpty() ? html + "<br/><br/>" + imageElement : html + imageElement;
}

QString RichText::buildImageTag(QString imageResourceName)
{
	return QString("<img src=\"%0\" alt=\"Image\" />").arg(imageResourceName);
}


QString RichText::formatToHTML(QString str)
{
	QString latexTag = "<latex>";
	QString footer = "</latex>";
	int headerSize = latexTag.size();
	if (str.contains(latexTag))
	{
		str = str.midRef(headerSize, str.count()-(headerSize+footer.size())).toString();
		std::ofstream myfile;
		myfile.open ("/tmp/mugenlatex.tex");
		myfile << str.toStdString().c_str();
		myfile.close();

		QString convertPref = QSettings().value("convertPath").toString();
		QString latexPref = QSettings().value("latexPath").toString();
		QString tex2imPref = QSettings().value("tex2imPath").toString();

		QFileInfo convert(convertPref);
		QString convertPath = convert.absoluteDir().absolutePath();

		QFileInfo latex(latexPref);
		QString latexPath = latex.absoluteDir().absolutePath();

		QString cmd("");

		cmd += "cd /tmp; rm -f /tmp/mugenlatex.png;";
		cmd += "export PATH=" + convertPath + ":$PATH;";
		cmd += "export PATH=" + latexPath + ":$PATH;";
		cmd += tex2imPref + " /tmp/mugenlatex.tex -p /tmp/mugenlatex.png 2> /dev/null";

		system(cmd.toAscii());
		str = "<img src='/tmp/mugenlatex.png'>";
	}

	//return "<p>" + str + "</p>"; //this spoiled alignment of content containing only images and no text
	return str;
}
